package com.faithbj.process.server;

import org.drools.SystemEventListenerFactory;
import org.jbpm.task.service.TaskService;
import org.jbpm.task.service.UserGroupCallbackManager;
import org.jbpm.task.service.hornetq.HornetQTaskServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@Component
public class TaskServer implements ApplicationContextAware {

    private static Logger log = LoggerFactory.getLogger(TaskServer.class);

    @Autowired
    @Qualifier("taskEmf")
    private EntityManagerFactory emf;

    private ApplicationContext applicationContext;

    @PostConstruct
    public void startup() throws IOException {
        TaskService taskService = new TaskService(emf, SystemEventListenerFactory.getSystemEventListener());
        InputStream usergroupsin = applicationContext.getResource("classpath:process/jbpm.usergroup.callback.properties").getInputStream();
        if (usergroupsin != null) {
            Properties callbackproperties = new Properties();
            try {
                callbackproperties.load(usergroupsin);
                UserGroupCallbackManager.getInstance().setCallbackFromProperties(callbackproperties);
                log.debug("Task service registered usergroup callback ...");
            } catch (Exception e) {
                log.error("Task service unable to register usergroup callback ...");
            }
        }
        HornetQTaskServer server = new HornetQTaskServer(taskService, 5445);
        Thread thread = new Thread(server);
        thread.start();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}